package com.sphsine.bip;

import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;

/**
 * BaseRequest
 *
 * @author HanQuinn
 * Date: 2024/2/28
 * Time: 11:20
 */
public class BaseRequest {

    private BasicHttpClientConnectionManager useCertConnManager;

    private BasicHttpClientConnectionManager noUseCertconnManager;

    protected BasicHttpClientConnectionManager getHttpClientConnectionManager(boolean useCert) throws NoSuchAlgorithmException {
        BasicHttpClientConnectionManager connManager;
        if (useCert) {
            if (useCertConnManager != null){
                connManager = this.useCertConnManager;
            }else {
                // 创建 SSLContext
                SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
//
                SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                        sslContext,
                        new String[]{"TLSv1"},
                        null,
                        new DefaultHostnameVerifier());

                connManager = new BasicHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                                .register("https", sslConnectionSocketFactory)
                                .build(),
                        null,
                        null,
                        null
                );
            }
        }
        else {
            if (noUseCertconnManager != null){
                connManager = this.noUseCertconnManager;
            }else {
                connManager = new BasicHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                                .build(),
                        null,
                        null,
                        null
                );
            }
        }
        return connManager;
    }
}
